package helper;

import play.Logger;

import java.io.*;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;


/**
 * 日期工具类.
 * <p/>
 * User: sujie
 * Date: 4/6/12
 * Time: 3:57 PM
 */
public class CSVUtils {

    public static File createCSVFile(List exportData, LinkedHashMap rowMapper, String filename) {

        File csvFile = null;
        BufferedWriter csvFileOutputStream = null;
        try {
            csvFile = File.createTempFile(filename, ".csv");
            Logger.info("创建 csvFile : %s ...." , csvFile.getAbsolutePath() + csvFile.getName());
            // GB2312使正确读取分隔符","
            csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(csvFile), "GB2312"), 1024);
            Logger.info("初始化  csvFileOutputStream ： %s ..." , csvFileOutputStream);
            // 写入文件头部
            for (Iterator propertyIterator = rowMapper.entrySet().iterator(); propertyIterator.hasNext();) {
                java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator
                        .next();
                csvFileOutputStream.write("\""
                        + propertyEntry.getValue().toString() + "\"");
                if (propertyIterator.hasNext()) {
                    csvFileOutputStream.write(",");
                }
            }
            Logger.info("写入文件头部结束 ....");
            csvFileOutputStream.newLine();
            Logger.info("开始写入文件内容 ....");
            // 写入文件内容
            for (Iterator iterator = exportData.iterator(); iterator.hasNext();) {
                // Object row = (Object) iterator.next();
                LinkedHashMap row = (LinkedHashMap) iterator.next();
                for (Iterator propertyIterator = row.entrySet().iterator(); propertyIterator.hasNext();) {
                    java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();
                    csvFileOutputStream.write("\""
                            +  propertyEntry.getValue().toString() + "\"");
                    if (propertyIterator.hasNext()) {
                        csvFileOutputStream.write(",");
                    }
                }
                if (iterator.hasNext()) {
                    csvFileOutputStream.newLine();
                }
            }
            csvFileOutputStream.flush();
            Logger.info("开始写入文件内容结束 ....");
        } catch (Exception e) {
            e.printStackTrace();
            Logger.info("导出CSV异常 ");
        } finally {
            try {
                csvFileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return csvFile;
    }
}
